package com.workflow.engine.demo.utils;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;

import java.util.Map;

/**
 * Created by houjinxin on 2017/2/25.
 */
public class RequestUtil {

    /**
     * 执行GET方法, 带Header与不带Header的方法
     *
     * @param requestUrlPrefix
     * @param requestParams
     * @return
     * @throws Exception
     */
    public static String executeGetMethod(String requestUrlPrefix, Map<String, String> requestParams, Map<String, String> headers) throws Exception {
        String requestUrl = requestUrlPrefix + (getEndStr(requestUrlPrefix).equals("?") ? "" : "?") + HttpHelper.mapJoinIncludeValueNull(requestParams, false, true);
        return HttpHelper.get(requestUrl, headers);
    }

    public static String executeGetMethod(String requestUrlPrefix, Map<String, String> requestParams) throws Exception {
        return executeGetMethod(requestUrlPrefix, requestParams, null);
    }

    /**
     * 执行Post方法, 带Header与不带Header的方法
     *
     * @param requestUrl
     * @param requestParams
     * @return
     * @throws Exception
     */
    public static String executePostMethod(String requestUrl, Map<String, String> requestParams, Map<String, String> headers) throws Exception {
        return HttpHelper.postBackString(requestParams, requestUrl, headers);
    }

    public static String executePostMethod(String requestUrl, Map<String, String> requestParams) throws Exception {
        return executePostMethod(requestUrl, requestParams, null);
    }

    /**
     * 获取URL最后一个字符
     * @param url
     * @return
     */
    private static String getEndStr(String url) {
        return url.substring(url.length() - 1, url.length());
    }

    /**
     * 需要根据HttpResponse进行判断的情况,使用下面两个方法
     * @param requestUrl
     * @param headers
     * @return
     * @throws Exception
     */
    public static HttpResponse sendGetRequest(String requestUrl, Map<String, String> requestParams, Map<String, String> headers) throws Exception {
        requestUrl = requestUrl + (getEndStr(requestUrl).equals("?") ? "" : "?") + HttpHelper.mapJoinIncludeValueNull(requestParams, false, true);
        HttpGet get = new HttpGet(requestUrl);
        HttpHelper.setHeaders(get, headers);
        return HttpHelper.exec(HttpHelper.getHttpClient(), get);
    }

    public static HttpResponse sendPostRequest(String requestUrl, Map<String, String> requestParams, Map<String, String> headers) throws Exception {
        HttpPost post = new HttpPost(requestUrl);
        HttpHelper.setEntity(post, requestParams);
        HttpHelper.setHeaders(post, headers);
        return HttpHelper.exec(HttpHelper.getHttpClient(), post);
    }

}
